package com.tansun.easycare.rule.policytree.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.tansun.easycare.rule.common.JsonMessage;
import com.tansun.easycare.rule.common.RuleBaseController;
import com.tansun.easycare.rule.policytree.model.PolicyTreeItem;
import com.tansun.easycare.rule.policytree.model.PolicyTreeModel;
import com.tansun.easycare.rule.policytree.model.PolicyTreeScene;
import com.tansun.easycare.rule.policytree.model.PolicyTreeVO;
import com.tansun.easycare.rule.policytree.service.PolicyTreeService;
import com.tansun.easycare.rule.rulemange.model.RuleManageVO;
import com.tansun.easycare.rule.rulemange.service.RuleManageService;
import com.tansun.easycare.rule.utils.JsonUtil;
import com.tansun.rule.common.RuleModelTypeEnum;
import com.tansun.rule.utils.LoggerManager;

/**
 * 策略树
 */
@Controller
@RequestMapping(value = "/ruleProj/policyTree")
public class PolicyTreeController extends RuleBaseController {

    @Autowired
    private RuleManageService ruleManageService;

    @Autowired
    private PolicyTreeService policyTreeService;

    private static final String DISPLAY = "display";

    private static final String EDIT = "edit";

    private static final String COMAPRE = "compare";

    /**
     * 列表页面
     *
     * @param projectCode 项目编码
     * @param param       查询策略树条件
     * @param map         ModelMap
     * @return 列表页面
     * @exception Exception 异常信息
     */
    @RequestMapping("index")
    public String index(HttpServletResponse response, HttpServletRequest request, String projectCode, RuleManageVO param, ModelMap map) throws Exception {

        param.setProjectCode(projectCode);
        param.setModelType(RuleModelTypeEnum.PolicyTree.code);
        PageInfo<RuleManageVO> page = this.ruleManageService.findRuleManageVO(param.getPage(), param);

        map.put("projectCode", this.getCurrProjectCode());
        map.put("page", page);
        map.put("searchVo", JsonUtil.object2json(param));
        return "rule/policytree/index";
    }

    /**
     * 跳转到明细页面
     *
     * @param decisionTreeId 策略树id
     * @param isedit         是否编辑
     * @param version        版本号
     * @param map            ModelMap
     * @return 明细页面
     * @exception Exception 异常
     */
    @RequestMapping("detail")
    public String detail(String policyTreeId, String isedit, String version, ModelMap map) throws Exception {
        if (DISPLAY.equals(isedit) || EDIT.equals(isedit) || COMAPRE.equals(isedit)) { //显示树信息
            PolicyTreeVO policyTreeVO = this.policyTreeService.getTreeInfo(policyTreeId, version);
            map.put("tree", policyTreeVO.getTree());
            map.put("version", policyTreeVO.getVersion());
            map.put("treeHtml", policyTreeVO.getTreeHtml());
            map.put("optionHtml", policyTreeVO.getOptionHtml());
            map.put("actionDatas", policyTreeVO.getActionDatas());

        }
        map.put("projectCode", this.getCurrProjectCode());
        map.put("isedit", isedit);
        return "rule/policytree/policyTreeDetail";
    }

    /**
     * 维护叶子弹出框
     *
     * @return 叶子页面
     */
    @RequestMapping("/leafDialog")
    public String leafDialog() {
        return "rule/policytree/leafDialog";
    }

    /**
     * 维护分支弹出框
     *
     * @param projectCode 项目编码
     * @param map         ModelMap
     * @return 分支页面
     */
    @RequestMapping("/branchDialog")
    public String branchDialog(String projectCode, ModelMap map) {
        map.put("projectCode", projectCode);
        return "rule/policytree/branchDialog";
    }

    /**
     * 获取所有叶子节点信息
     *
     * @param page 分页信息
     * @return 所有叶子节点分页数据
     * @exception Exception 异常
     */
    @RequestMapping("getLeaves")
    @ResponseBody
    public List<Map<String, String>> getLeaves(String code, String version, HttpServletRequest request) throws Exception {
        if (StringUtils.isBlank(code) || StringUtils.isBlank(version)) {
            return null;
        }
        String projectCode = this.getCurrProjectCode();
        PolicyTreeModel entity = this.policyTreeService.findPolicyTreeModel(code, version, projectCode);

        if (entity == null || entity.getPolicyTreeItem() == null) {
            return null;
        }
        List<Map<String, String>> rows = getLeafRow(entity);
        return rows;
    }

    /**
     * 将叶子节点数据拼成4个一行
     *
     * @param entity 策略树实体
     * @return 叶子节点数据列表
     */
    private List<Map<String, String>> getLeafRow(PolicyTreeModel entity) {
        List<PolicyTreeItem> leaves = new ArrayList<PolicyTreeItem>();
        List<PolicyTreeItem> nodes = entity.getPolicyTreeItem();
        List<PolicyTreeScene> actionScenes = entity.getActionScene();
        Map<String, String> controlValueMap = new HashMap<String, String>(); //{actionSceneId,controlValue}
        for (PolicyTreeItem node : nodes) {
            if (!"true".equals(node.getIsLeaf())) {
                continue;
            }
            leaves.add(node);
            //获取动作场景Id与值的映射关系
            for (PolicyTreeScene actionScene : actionScenes) {
                if (actionScene.getId().equals(node.getActionSceneId())) {
                    controlValueMap.put(actionScene.getId(), actionScene.getControlValue());
                }
            }
        }

        int colNum = 4;
        List<Map<String, String>> rows = new ArrayList<Map<String, String>>();
        for (int rowId = 0; rowId < leaves.size() / 4 + 1; rowId++) { //row
            Map<String, String> row = new HashMap<String, String>();
            for (int colId = 0; colId < colNum; colId++) {
                int i = rowId * 4 + colId;
                if (i < leaves.size()) {
                    row.put("id" + colId, leaves.get(i).getId());
                    row.put("index" + colId, i + 1 + "");
                    row.put("value" + colId, controlValueMap.get(leaves.get(i).getActionSceneId()));
                    row.put("name" + colId, leaves.get(i).getName());
                }
            }
            rows.add(row);
        }
        return rows;
    }

    /**
     * 保存策略树
     *
     * @param treeEntity 策略树实体
     * @return 操作结果
     */
    @RequestMapping("saveOrUpdate")
    public @ResponseBody
    JsonMessage saveOrUpdate(@RequestBody PolicyTreeModel treeEntity) {
        JsonMessage ret = new JsonMessage();
        try {
            policyTreeService.saveOrUpdate(treeEntity);
            //ret.setData(treeId);
        } catch (Exception e) {
            LoggerManager.error(e.getMessage(), e, this.getClass());
            ret.setResult(false);
            ret.setMessage(e.getMessage());
        }
        return ret;
    }

    @Override
    public void setRuleBizService() {
        // TODO Auto-generated method stub
        super.setRuleBaseService(policyTreeService);
    }


}
